<?php

namespace Biz\service\advertisement;

use Doraemon\tools\HhzEnv;
use Exception;

class AdModel implements \ArrayAccess
{
    public function __construct($data = []) {
        foreach ($data as $key => $value) {
            $this->{$key} = $value;
        }
    }

    public function __get($key)
    {
        return $this->{$key} ?? null;
    }

    public function __set($key, $value)
    {
        $this->{$key} = $value;
    }

    public function offsetSet($offset, $value) {
        $this->{$offset} = $value;
    }

    public function offsetExists($offset): bool
    {
        return isset($this->{$offset});
    }

    public function offsetUnset($offset) {
        unset($this->{$offset});
    }

    public function offsetGet($offset) {
        return $this->{$offset} ?? null;
    }


    /**
     * @throws Exception
     */
    public static function setConf($path, $data)
    {
        self::writeable($path);
        $conf = var_export($data, true);
        $content = <<<CONTENT
<?php

return $conf

;
CONTENT;
        return file_put_contents($path, $content, LOCK_EX);
    }

    public static function writeable($path)
    {
        if (file_exists($path) && !is_writeable($path)) throw new Exception($path . ' 文件不可写,确认权限');
    }

    /**
     * @throws Exception
     */
    public static function opAuth($throws = true)
    {
        if (!$throws) return HhzEnv::isShopTest();
        if (!HhzEnv::isShopTest()) throw new \Exception('研发操作');
    }
}